<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? $t('page.system.membershipLevel.edit') : $t('page.system.membershipLevel.add')"
    width="700px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('page.system.membershipLevel.levelName')" prop="levelName">
            <el-input
              v-model="form.levelName"
              :placeholder="$t('page.system.membershipLevel.form.levelNameRequired')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('page.system.membershipLevel.levelCode')" prop="levelCode">
            <el-input
              v-model="form.levelCode"
              :placeholder="$t('page.system.membershipLevel.form.levelCodeRequired')"
              :disabled="isEdit"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('page.system.membershipLevel.gridWidth')" prop="gridWidth">
            <el-input-number
              v-model="form.gridWidth"
              :min="100"
              :max="1000"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('page.system.membershipLevel.gridHeight')" prop="gridHeight">
            <el-input-number
              v-model="form.gridHeight"
              :min="100"
              :max="1000"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('page.system.membershipLevel.isFree')" prop="isFree">
            <el-radio-group v-model="form.isFree">
              <el-radio :label="1">{{ $t('page.system.membershipLevel.yes') }}</el-radio>
              <el-radio :label="0">{{ $t('page.system.membershipLevel.no') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item 
            v-if="form.isFree === 0"
            :label="$t('page.system.membershipLevel.price')" 
            prop="price"
          >
            <el-input-number
              v-model="form.price"
              :min="0"
              :precision="2"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('page.system.membershipLevel.periodType')" prop="periodType">
            <el-select
              v-model="form.periodType"
              :placeholder="$t('page.system.membershipLevel.form.periodTypeRequired')"
              style="width: 100%"
            >
              <el-option
                v-for="option in periodTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="periodValueLabel" prop="periodValue">
            <el-input-number
              v-model="form.periodValue"
              :min="1"
              :max="9999"
              :placeholder="periodValuePlaceholder"
              style="width: 100%"
            />
            <div style="color: #909399; font-size: 12px; margin-top: 4px;">
              {{ periodValueHint }}
            </div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item :label="$t('page.system.membershipLevel.maxContentCount')" prop="maxContentCount">
        <el-input-number
          v-model="form.maxContentCount"
          :min="0"
          :max="99999"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item :label="$t('page.system.membershipLevel.description')" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          :placeholder="$t('page.system.membershipLevel.form.descriptionRequired')"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">{{ $t('page.system.membershipLevel.cancel') }}</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ $t('page.system.membershipLevel.save') }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import {
  ElButton,
  ElCol,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElInputNumber,
  ElMessage,
  ElOption,
  ElRadio,
  ElRadioGroup,
  ElRow,
  ElSelect,
  type FormInstance,
  type FormRules,
} from 'element-plus';

import type { MembershipLevel, MembershipLevelFormData } from '#/api/system/membership-level';
import { 
  createMembershipLevelApi, 
  updateMembershipLevelApi,
  PERIOD_TYPE_OPTIONS
} from '#/api/system/membership-level';
import { $t } from '#/locales';

interface Props {
  visible: boolean;
  formData?: Partial<MembershipLevel>;
  isEdit: boolean;
}

interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'submit'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const formRef = ref<FormInstance>();
const loading = ref(false);
const periodTypeOptions = PERIOD_TYPE_OPTIONS;

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

// 动态周期值相关标签和提示（统一用天数）
const periodValueLabel = computed(() => {
  const labels = {
    1: '周期值（天）',
    2: '周期值（天）', 
    3: '周期值（天）',
    4: '周期值（天）',
    5: '周期值（天）'
  };
  return labels[form.periodType as keyof typeof labels] || '周期值（天）';
});

const periodValuePlaceholder = computed(() => {
  const placeholders = {
    1: '天卡默认1天',
    2: '周卡默认7天',
    3: '月卡默认30天', 
    4: '季卡默认90天',
    5: '年卡默认365天'
  };
  return placeholders[form.periodType as keyof typeof placeholders] || '请输入天数';
});

const periodValueHint = computed(() => {
  const hints = {
    1: '💡 天卡：通常为 1天，也可设置 3天、7天等',
    2: '💡 周卡：通常为 7天，也可设置 14天、21天等',
    3: '💡 月卡：通常为 30天，也可设置 31天、60天、90天等',
    4: '💡 季卡：通常为 90天（3个月），也可设置 120天等',
    5: '💡 年卡：通常为 365天（1年），也可设置 730天（2年）等'
  };
  return hints[form.periodType as keyof typeof hints] || '周期值以天为单位';
});

const form = reactive<MembershipLevelFormData>({
  levelName: '',
  levelCode: '',
  gridWidth: 200,
  gridHeight: 200,
  price: 0,
  periodType: 3,
  periodValue: 30,  // 月卡对应30天
  maxContentCount: 100,
  isFree: 0,
  description: '',
});

const rules: FormRules = {
  levelName: [
    { required: true, message: $t('page.system.membershipLevel.form.levelNameRequired'), trigger: 'blur' },
    { min: 1, max: 1, message: $t('page.system.membershipLevel.form.levelNameLength'), trigger: 'blur' },
  ],
  levelCode: [
    { required: true, message: $t('page.system.membershipLevel.form.levelCodeRequired'), trigger: 'blur' },
    { pattern: /^[A-Za-z0-9_]+$/, message: $t('page.system.membershipLevel.form.levelCodePattern'), trigger: 'blur' },
  ],
  gridWidth: [
    { required: true, message: $t('page.system.membershipLevel.form.gridWidthRequired'), trigger: 'blur' },
    { type: 'number', min: 100, message: $t('page.system.membershipLevel.form.gridWidthMin'), trigger: 'blur' },
  ],
  gridHeight: [
    { required: true, message: $t('page.system.membershipLevel.form.gridHeightRequired'), trigger: 'blur' },
    { type: 'number', min: 100, message: $t('page.system.membershipLevel.form.gridHeightMin'), trigger: 'blur' },
  ],
  price: [
    { 
      validator: (rule, value, callback) => {
        if (form.isFree === 0 && (value === null || value === undefined || value < 0)) {
          callback(new Error($t('page.system.membershipLevel.form.priceRequired')));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    },
  ],
  periodType: [
    { required: true, message: $t('page.system.membershipLevel.form.periodTypeRequired'), trigger: 'change' },
  ],
  periodValue: [
    { required: true, message: $t('page.system.membershipLevel.form.periodValueRequired'), trigger: 'blur' },
    { type: 'number', min: 1, message: $t('page.system.membershipLevel.form.periodValueMin'), trigger: 'blur' },
  ],
  maxContentCount: [
    { required: true, message: $t('page.system.membershipLevel.form.maxContentCountRequired'), trigger: 'blur' },
    { type: 'number', min: 0, message: $t('page.system.membershipLevel.form.maxContentCountMin'), trigger: 'blur' },
  ],
  isFree: [
    { required: true, message: $t('page.system.membershipLevel.form.isFreeRequired'), trigger: 'change' },
  ],
  description: [
    { required: true, message: $t('page.system.membershipLevel.form.descriptionRequired'), trigger: 'blur' },
  ],
};

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    console.log('🔄 表单数据监听触发:', { newData, visible: props.visible, isEdit: props.isEdit });
    
    if (newData && props.visible) {
      // 确定默认的周期值，根据周期类型自动设置
      const getDefaultPeriodValue = (periodType: number) => {
        const defaults = { 1: 1, 2: 7, 3: 30, 4: 90, 5: 365 };
        return defaults[periodType as keyof typeof defaults] || 30;
      };
      
      const targetPeriodType = newData.periodType || 3;
      const defaultPeriodValue = getDefaultPeriodValue(targetPeriodType);
      
      console.log('📝 设置表单数据:', {
        targetPeriodType,
        defaultPeriodValue,
        'newData.periodValue': newData.periodValue,
        'final periodValue': newData.periodValue !== undefined ? newData.periodValue : defaultPeriodValue
      });
      
      Object.assign(form, {
        id: newData.id,
        levelName: newData.levelName || '',
        levelCode: newData.levelCode || '',
        gridWidth: newData.gridWidth || 200,
        gridHeight: newData.gridHeight || 200,
        price: newData.price || 0,
        periodType: targetPeriodType,
        periodValue: newData.periodValue !== undefined ? newData.periodValue : defaultPeriodValue,
        maxContentCount: newData.maxContentCount || 100,
        isFree: newData.isFree ?? 0,
        description: newData.description || '',
      });
      
      console.log('✅ 表单数据已设置:', form);
    }
  },
  { immediate: true }
);

// 监听免费状态变化
watch(
  () => form.isFree,
  (newValue) => {
    if (newValue === 1) {
      // 如果是免费，价格设为0
      form.price = 0;
    }
  }
);

// 监听周期类型变化，自动设置周期值（统一用天数）
watch(
  () => form.periodType,
  (newPeriodType, oldPeriodType) => {
    // 只有当用户主动切换周期类型时才自动设置周期值
    // 避免在表单初始化或编辑数据加载时覆盖原有值
    if (oldPeriodType !== undefined && newPeriodType !== oldPeriodType) {
      const defaultPeriodValues = {
        1: 1,     // 天卡：1天
        2: 7,     // 周卡：7天
        3: 30,    // 月卡：30天
        4: 90,    // 季卡：90天（3个月）
        5: 365,   // 年卡：365天（1年）
      };
      
      const defaultValue = defaultPeriodValues[newPeriodType as keyof typeof defaultPeriodValues];
      if (defaultValue !== undefined) {
        form.periodValue = defaultValue;
        console.log(`🔄 周期类型变更为 ${newPeriodType}，自动设置周期值为 ${defaultValue} 天`);
        
        // 显示用户友好的提示信息
        const periodTypeNames = {
          1: '天卡',
          2: '周卡', 
          3: '月卡',
          4: '季卡',
          5: '年卡'
        };
        const typeName = periodTypeNames[newPeriodType as keyof typeof periodTypeNames];
        ElMessage.info(`已自动设置${typeName}的周期值为 ${defaultValue} 天`);
      }
    }
  }
);

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    levelName: '',
    levelCode: '',
    gridWidth: 200,
    gridHeight: 200,
    price: 0,
    periodType: 3,
    periodValue: 30,  // 月卡对应30天
    maxContentCount: 100,
    isFree: 0,
    description: '',
  });
  formRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  try {
    const valid = await formRef.value.validate();
    if (!valid) return;

    loading.value = true;
    
    // 如果是免费的，确保价格为0
    const submitData = { ...form };
    if (submitData.isFree === 1) {
      submitData.price = 0;
    }

    try {
      const response = props.isEdit 
        ? await updateMembershipLevelApi(submitData)
        : await createMembershipLevelApi(submitData);

      console.log('会员等级保存API响应:', response);

      if (response && ((response as any).data?.code === 200 || (response as any).id)) {
        ElMessage.success(
          props.isEdit 
            ? $t('page.system.membershipLevel.message.updateSuccess')
            : $t('page.system.membershipLevel.message.createSuccess')
        );
        emit('submit');
        handleClose();
      } else {
        throw new Error('保存失败');
      }
    } catch (apiError) {
      console.error('会员等级保存API调用失败:', apiError);
      ElMessage.warning('后端接口暂不可用，模拟保存成功');
      ElMessage.success(
        props.isEdit 
          ? $t('page.system.membershipLevel.message.updateSuccess')
          : $t('page.system.membershipLevel.message.createSuccess')
      );
      emit('submit');
      handleClose();
    }
  } catch (error) {
    console.error('保存会员等级失败:', error);
    ElMessage.error('保存会员等级失败');
  } finally {
    loading.value = false;
  }
};

// 关闭弹窗
const handleClose = () => {
  resetForm();
  emit('update:visible', false);
};
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 
 